<?php
declare(strict_types = 1);

namespace app\model;

use think\db\concern\WhereQuery;
use think\Model;

/**
 * @mixin \think\Model
 */
class User extends Model
{
    protected $schema = [
        'id'             => 'int',
        'username'       => 'string',
        'avatar'         => 'string',
        'nickname'       => 'string',
        'password'       => 'string',
        'login_ip'       => 'string',
        'created_time'   => 'timestamp',
        'wechat_open_id' => 'string',
        'is_delete'      => 'boolean',
    ];

    public function getUserById($id)
    {
        $user = self::findOrEmpty($id);
        if (empty($user)) {
            return [];
        }
        return $user->toArray();
    }

    public function getByOpenId($openId): array
    {
        $user = self::where('wechat_open_id', $openId)->findOrEmpty();

        if (empty($user)) {
            return [];
        }

        return $user->toArray();
    }

    public function findByIds(array $ids)
    {
        $users = self::select($ids);
        if ($users->isEmpty()) {
            return [];
        }
        return $users->toArray();
    }

    public function getByUsername($username)
    {
        $user = self::where('username', $username)->findOrEmpty();
        if (empty($user)) {
            return [];
        }
        return $user->toArray();
    }

    public function findAllWeChatUser()
    {
        $users = self::whereNotNull('wechat_open_id')->select();
        if (empty($users)) {
            return [];
        }
        return $users->toArray();
    }

    public function getByFields($field, $value)
    {
        $user = self::where($field, $value)->findOrEmpty();
        if (empty($user)) {
            return [];
        }
        return $user->toArray();
    }

    public function countUser(array $conditions)
    {
        return $this->countData($conditions);
    }

    public function searchUsers(array $conditions, array $orderBy = [], $start = 0, $limit = 20)
    {
        $users = $this->searchData($conditions, $orderBy, $start, $limit);

        if (empty($users)) {
            return [];
        }
        return $users->toArray();
    }

    public function declares()
    {
        return [
            'orderBy' => [
                'id',
                'created_time'
            ],
            'conditions' => [
                'id' => ['=', 'id'],
                'ids' => ['in', 'id'],
                'nickname' => ['=', 'nickname'],
                'nicknameLike' => ['rightLike', 'nickname'],
                'username' => ['=', 'username'],
                'usernameLike' => ['rightLike', 'username'],
            ]
        ];
    }
}
